var StorageKey = {
    "MUTE_MAPPINGS": "MUTE_MAPPINGS",
};
var MuteType = {
    "HOST": "HOST",
    "URL": "URL",
};
var StorageKeys = Object.values(StorageKey);
var MuteTypes = Object.values(MuteType);


chrome.action.onClicked.addListener(toggleMuteByTab);

function getHost(url) {
    if (!/^\w+:\/\//.test(url)) {
        url = "http://" + url;
    }
    let obj = new URL(url);
    return obj.host;
}

async function toggleMuteByTab(tab) {
	console.log(`toggle mute`, tab.url);
    let result = await chrome.storage.sync.get(StorageKeys);
    let mappings = JSON.parse(result[StorageKey.MUTE_MAPPINGS] || "[]");
    let existed = false;
    for (let i = mappings.length - 1; i >= 0; --i) {
        let mapping = mappings[i];
        let matched = false;
        if (mapping[1] === MuteType.HOST) {
            matched = getHost(tab.url) === getHost(mapping[0]);
        } else {
            matched = tab.url === mapping[0];
        }
        if (matched) {
            existed = true;
            mappings.splice(i, 1);
        }
    }
    if (!existed) {
        mappings.push([tab.url, MuteType.HOST]);
    }
    await chrome.storage.sync.set({
        [StorageKey.MUTE_MAPPINGS]: JSON.stringify(mappings),
    });
    updateSelectedUrl(tab.id);
}

chrome.tabs.onActivated.addListener(function (info) {
    updateSelectedUrl(info.tabId);
});

chrome.tabs.onUpdated.addListener(async function (tabId, change, tab) {
    // 由用户手动设置状态
    if (change.mutedInfo?.reason == "user") {
        await toggleMuteByTab(tab);
        return;
    }
    updateSelectedUrl(tabId);
});

async function updateSelectedUrl(tabId) {
    let muted;
    let tabInfo = await chrome.tabs.get(tabId);
    if (tabInfo?.url) {
        let result = await chrome.storage.sync.get(StorageKeys);
        let mappings = JSON.parse(result[StorageKey.MUTE_MAPPINGS] || "[]");
        muted = mappings.some(mapping => {
            var url = mapping[0];
            var type = mapping[1];
            if (type == MuteType.HOST) {
                return getHost(url) === getHost(tabInfo.url);
            } else {
                return url === tabInfo.url;
            }
        });
    }
    await chrome.tabs.update(tabId, { muted });
    await chrome.action.setIcon({
        path: muted ? "/assets/icon@muted.png" : "/assets/icon.png",
        tabId: tabId,
    });
}


//////////// commands

chrome.commands.onCommand.addListener(async (command) => {
    console.log(`Command: ${command}`);
    switch (command) {
        case "ToggleMute": {
            toggleMute();
            break;
        }
    }
});

async function toggleMute() {
    let tabs = await chrome.tabs.query({
        active: true,
        currentWindow: true
    });
    let tab = tabs[0];
    if (!tab) return;
    await toggleMuteByTab(tab);
}